package com.issac.webflux.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: ywy
 * @date: 2023-10-29
 * @desc:
 */
@SpringBootApplication
public class WebFluxApplication {

    public static final List<Employee> employees = new ArrayList<>();

    static {
        employees.add(new Employee(1));
        employees.add(new Employee(2));

        employees.add(new Employee(3));
        employees.add(new Employee(4));

        employees.add(new Employee(5));

    }

    public static void main(String[] args) {
        SpringApplication.run(WebFluxApplication.class, args);
    }

    @RestController
    class EmployeeController {


        @GetMapping(value = "greeting", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
        public Flux<String> greeting() {
            return Flux.just("hello world");
        }

        @GetMapping(value = "sse1", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
        public Flux<String> sse1() {
            return Flux.interval(Duration.ofMillis(1000))
                    .map(val -> val.toString());
        }

        @CrossOrigin
        @GetMapping(value = "sse2", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
        public Flux<ServerSentEvent<String>> sse2() {
            return Flux.interval(Duration.ofMillis(1000))
                    .map(val -> {
                        return ServerSentEvent.<String>builder()
//                                .id(UUID.randomUUID().toString())
                                .event("ping")
                                .data(val.toString())
                                .build();
                    });
        }

        @GetMapping(value = "employees", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
        public Flux<Employee> findAll() {
            return Flux.range(1, 5).map(val -> {
                return employees.stream().filter(employee -> employee.getId() == val).findFirst().get();
            }).delayElements(Duration.ofMillis(1000));
        }
    }
}
